package com.tanhua.manage.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.manage.domain.UserFreezing;
import com.tanhua.manage.mapper.UserFreezingMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Slf4j
/**
 * 监听消失的key
 */
public class KeyExpiredListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired(required = false)
    private UserFreezingMapper userFreezingMapper;

    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String key = new String(message.getBody(), StandardCharsets.UTF_8);

        //判断该key是否是userFreezing_开头
        if(key.startsWith("userFreezing_")) {

            //解析数据 得到消失的key的userId信息
            String regEx = "[^0-9]";
            Pattern compile = Pattern.compile(regEx);
            Matcher matcher = compile.matcher(key);
            Long userId = Long.valueOf(matcher.replaceAll("").trim());

            //更改userInfo信息
            UserInfo userInfo = new UserInfo();
            userInfo.setUserStatus("1");
            userInfo.setId(userId);

            userInfoApi.update(userInfo);

            //更改userFreezing信息
            QueryWrapper<UserFreezing> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId).eq("is_freezing",1);
            UserFreezing userFreezing = new UserFreezing();
            userFreezing.setUserId(userId.intValue());
            userFreezing.setIsFreezing(2);
            userFreezing.setUpdated(new Date());
            userFreezingMapper.update(userFreezing, queryWrapper);

            log.info("=========> 监听到key：" + key + " 刚刚消失了！");
            log.info("=========> 监听到userId为：" + userId);
        }
    }
}
